package com.ziyun.erp.modules.purchase.service.impl;

import com.ziyun.erp.common.e.purchase.MaterialSupplierStatusEnum;
import com.ziyun.erp.common.e.purchase.PurchaseApplyStatusEnum;
import com.ziyun.erp.common.utils.PurchaseUtils;
import com.ziyun.erp.modules.material.entity.MaterialEntity;
import com.ziyun.erp.modules.purchase.entity.ErpStockLogEntity;
import com.ziyun.erp.modules.purchase.entity.StorePurchaseApplyDetailEntity;
import com.ziyun.erp.modules.purchase.entity.dto.StorePurchaseApplyDto;
import com.ziyun.erp.modules.purchase.service.ErpStockLogService;
import com.ziyun.erp.modules.purchase.service.StorePurchaseApplyDetailService;
import io.renren.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.ziyun.erp.modules.purchase.dao.StorePurchaseApplyDao;
import com.ziyun.erp.modules.purchase.entity.StorePurchaseApplyEntity;
import com.ziyun.erp.modules.purchase.service.StorePurchaseApplyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 门店采购申请
 *
 * @author guizhao
 * @email
 * @date 2018-09-26 13:28:47
 */
@Service("storePurchaseApplyService")
public class StorePurchaseApplyServiceImpl extends ServiceImpl<StorePurchaseApplyDao, StorePurchaseApplyEntity> implements StorePurchaseApplyService {

    @Autowired
    private StorePurchaseApplyDetailService storePurchaseApplyDetailService;

    @Autowired
    private ErpStockLogService erpStockLogService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<StorePurchaseApplyEntity> page = this.selectPage(
                new Query<StorePurchaseApplyEntity>(params).getPage(),
                new EntityWrapper<StorePurchaseApplyEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insertApply(StorePurchaseApplyDto storePurchaseApplyDto) {
        int sellerId = storePurchaseApplyDto.getStorePurchaseApplyEntity().getSellerId();
        StorePurchaseApplyEntity storePurchaseApplyEntity = storePurchaseApplyDto.getStorePurchaseApplyEntity();
        // 采购申请单号
        String purchaseApplyNo = PurchaseUtils.producePurchaseApplyNo(sellerId);

        //判断采购申请单号是否重复
        boolean isRepeat = false;
        do {
            List<StorePurchaseApplyEntity> storePurchaseApplyEntityList = baseMapper.selectList(
                    new EntityWrapper<StorePurchaseApplyEntity>().eq("apply_no",purchaseApplyNo)
            );
            if(storePurchaseApplyEntityList != null && storePurchaseApplyEntityList.size() > 0){
                isRepeat = true;
                purchaseApplyNo = PurchaseUtils.producePurchaseApplyNo(sellerId);
            }else{
                isRepeat = false;
            }
        }while (isRepeat);
        storePurchaseApplyEntity.setApplyNo(purchaseApplyNo);
        storePurchaseApplyEntity.setStatus(PurchaseApplyStatusEnum.WAIT_AUDIT.toInt());
        storePurchaseApplyEntity.setSellerId(sellerId);


        // 采购总价
        BigDecimal totalMoney = new BigDecimal(0);

        // 采购申请明细
        List<StorePurchaseApplyDetailEntity> detialListSave = new ArrayList<>();
        List<StorePurchaseApplyDetailEntity> storePurchaseApplyDetailEntityList =  storePurchaseApplyDto.getStorePurchaseApplyDetailEntityList();
        for(StorePurchaseApplyDetailEntity storePurchaseApplyDetailEntity:storePurchaseApplyDetailEntityList){
            if(StringUtil.isNotEmpty(storePurchaseApplyDetailEntity.getRemark())){
                storePurchaseApplyDetailEntity.setRemark(storePurchaseApplyDetailEntity.getRemark().trim());
            }
            totalMoney = totalMoney.add(storePurchaseApplyDetailEntity.getTotalMoney());

            // 单价
            BigDecimal  unitPrice =  storePurchaseApplyDetailEntity.getTotalMoney()
                    .divide(storePurchaseApplyDetailEntity.getMaterialQuantity(),4,BigDecimal.ROUND_HALF_UP);
            storePurchaseApplyDetailEntity.setUnitMoney(unitPrice);

            detialListSave.add(storePurchaseApplyDetailEntity);
        }

        storePurchaseApplyEntity.setTotalMoney(totalMoney.setScale(2,BigDecimal.ROUND_HALF_UP));

        baseMapper.insert(storePurchaseApplyEntity);
        storePurchaseApplyDetailService.saveBatch(detialListSave,storePurchaseApplyEntity);
        ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
        erpStockLogEntity.setBillNo(storePurchaseApplyEntity.getApplyNo());
        erpStockLogEntity.setType(1);
        erpStockLogEntity.setCreateName(storePurchaseApplyEntity.getCreateName());
        erpStockLogEntity.setLogText("采购申请提交");
        erpStockLogService.saveBatch(erpStockLogEntity);
        return R.ok();
    }

    @Override
    public void querylistPage(Page<StorePurchaseApplyEntity> page, Map<String, Object> params) {
        List<StorePurchaseApplyEntity> records = baseMapper.querylistPage(page,params);
        page.setRecords(records);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R audit(StorePurchaseApplyDto storePurchaseApplyDto) {
        StorePurchaseApplyEntity storePurchaseApplyEntity = storePurchaseApplyDto.getStorePurchaseApplyEntity();

        StorePurchaseApplyEntity check = baseMapper.selectById(storePurchaseApplyEntity.getApplyId());
        if(check == null || check.getStatus() != PurchaseApplyStatusEnum.WAIT_AUDIT.toInt()){
            return R.error("当前采购申请单状态不允许审核通过！");
        }
        Map<String,Object> updateApplyMap = new HashMap<>();
        updateApplyMap.put("tax",storePurchaseApplyEntity.getTax());
        updateApplyMap.put("status",PurchaseApplyStatusEnum.ALREADY_AUDIT.toInt());
        updateApplyMap.put("auditRemark",storePurchaseApplyEntity.getAuditRemark());
        updateApplyMap.put("checkName",UserUtil.getCurrentUser().getUsername());
        updateApplyMap.put("checkTime",new Date());

        // 采购总价
        BigDecimal totalMoney = new BigDecimal(0);

        // 采购申请明细
        List<StorePurchaseApplyDetailEntity> storePurchaseApplyDetailEntityList =  storePurchaseApplyDto.getStorePurchaseApplyDetailEntityList();

        for(StorePurchaseApplyDetailEntity storePurchaseApplyDetailEntity:storePurchaseApplyDetailEntityList){
            totalMoney = totalMoney.add(storePurchaseApplyDetailEntity.getTotalMoney());

            Map<String,Object> updateDetailMap = new HashMap<>();
            updateDetailMap.put("totalMoney",storePurchaseApplyDetailEntity.getTotalMoney());
            updateDetailMap.put("supplierId",storePurchaseApplyDetailEntity.getSupplierId());
            // 单价
            BigDecimal  unitPrice =  storePurchaseApplyDetailEntity.getTotalMoney()
                    .divide(storePurchaseApplyDetailEntity.getMaterialQuantity(),4,BigDecimal.ROUND_HALF_UP);
            updateDetailMap.put("unitMoney",unitPrice.doubleValue());

            storePurchaseApplyDetailService.updateByMap(updateDetailMap,storePurchaseApplyDetailEntity.getApplyDetailId());
        }

        updateApplyMap.put("totalMoney",totalMoney.setScale(2,BigDecimal.ROUND_HALF_UP));

        baseMapper.updateByMap(updateApplyMap,storePurchaseApplyEntity.getApplyId());
        ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
        erpStockLogEntity.setBillNo(storePurchaseApplyEntity.getApplyNo());
        erpStockLogEntity.setLogText("采购申请的审核");
        erpStockLogEntity.setCreateName(UserUtil.getCurrentUser().getUsername());
        erpStockLogEntity.setType(1);
        erpStockLogService.saveBatch(erpStockLogEntity);

        return R.ok();
    }

    @Override
    public R reject(StorePurchaseApplyDto storePurchaseApplyDto) {
        StorePurchaseApplyEntity storePurchaseApplyEntity = storePurchaseApplyDto.getStorePurchaseApplyEntity();
        StorePurchaseApplyEntity check = baseMapper.selectById(storePurchaseApplyEntity.getApplyId());
        if(check == null || check.getStatus() != PurchaseApplyStatusEnum.WAIT_AUDIT.toInt()){
            return R.error("当前采购申请单状态不允许审核通过！");
        }
        Map<String, Object> updateStoreMaterialInOutInMap = new HashMap<>();
        updateStoreMaterialInOutInMap.put("status",PurchaseApplyStatusEnum.REJECT.toInt());
        updateStoreMaterialInOutInMap.put("checkName",UserUtil.getCurrentUser().getUsername());
        updateStoreMaterialInOutInMap.put("checkTime",new Date());
        baseMapper.updateByMap(updateStoreMaterialInOutInMap,check.getApplyId());
        ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
        erpStockLogEntity.setType(1);
        erpStockLogEntity.setCreateName(UserUtil.getCurrentUser().getUsername());
        erpStockLogEntity.setLogText("采购申请审批驳回操作");
        erpStockLogEntity.setBillNo(storePurchaseApplyEntity.getApplyNo());
        erpStockLogService.saveBatch(erpStockLogEntity);
        return R.ok("驳回成功");
    }

    @Override
    public PageUtils selectAll(Map<String, Object> params) {
        String getapplyNo = params.get("applyNo").toString();
        if(getapplyNo!=""){
            ((LinkedHashMap) params).put("page",1);
            int totalCount = baseMapper.getqueryCountByname(getapplyNo);
            int current = Integer.parseInt(params.get("page").toString());
            int size = Integer.parseInt(params.get("limit").toString());
            params.put("offset", (current - 1) * size);
            params.put("limit", size);
            List<StorePurchaseApplyEntity> list = baseMapper.selectAll(params);
            return new PageUtils(list, totalCount, size, current);
        }else{
            int totalCount = baseMapper.getqueryCount();
            int current = Integer.parseInt(params.get("page").toString());
            int size = Integer.parseInt(params.get("limit").toString());
            params.put("offset", (current - 1) * size);
            params.put("limit", size);
            List<StorePurchaseApplyEntity> list = baseMapper.selectAll(params);
            return new PageUtils(list, totalCount, size, current);
        }
    }

    @Override
    public Integer updateFinase(Integer applyId) {
        return baseMapper.updateFinase(applyId);
    }

    @Override
    public Integer updateFinaseCheck(Integer applyId) {
        return baseMapper.updateFinaseCheck(applyId);
    }

    @Override
    public Integer updateFinaseCheckOnePay(Integer applyId) {
        return baseMapper.updateFinaseCheckOnePay(applyId);
    }

    @Override
    public Integer updateFinaseN(Integer applyId) {
        return baseMapper.updateFinaseN(applyId);
    }

    @Override
    public R BatchAuditAll(Object[] obj) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < obj.length; i++) {
            if (i == obj.length - 1) {
                sb.append(obj[i]);
            } else {
                sb.append(obj[i] + ",");
            }
        }
        Integer integer = baseMapper.BatchAuditAll(sb);
        if (integer <= 0) {
            return R.error("批量审批失败");
        }
        return R.ok();
    }

    @Override
    public R BulkPaymentAll(Object[] obj) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < obj.length; i++) {
            if (i == obj.length - 1) {
                sb.append(obj[i]);
            } else {
                sb.append(obj[i] + ",");
            }
        }
        Integer integer = baseMapper.BulkPaymentAll(sb);
        if (integer <= 0) {
            return R.error("批量审批失败");
        }
        return R.ok();
    }
}
